from openpyxl import Workbook
import os
import re

wb = Workbook()
ws = wb.active
ws.title = 'iOSString'

ws.cell(row=1, column=1).value = 'key'

urlList = []
valueList = []
keyList = []
# savepath = input('请输入需要保存的路径:')



def __getfilename(path):

    f_list = os.listdir(path)
    for i in f_list:
        if os.path.splitext(i)[1] == '.lproj':
            url = path + '/' + i + '/' + 'Localizable.strings'
            urlList.append(url)
            valueList.append(os.path.splitext(i)[0])

    #  TODO:这里应该要用线程控制  目前还不会
    for i in f_list:
        print("files : "+i)
        if ".lproj" in i:
        
            url = path + '/' + i + '/' + 'Localizable.strings'
            print("deal path: " + url)
            __dealbasefile(url)


#  处理key值 因为后面要遍历查询
def __dealbasefile(path):

    with open(path) as f:
        context = f.read()
        partten = re.compile(r'"(.*)" = "(.*)";')
        result = partten.findall(context)

        for i in range(len(result)):
            ws.cell(row=i + 2, column=1).value = result[i][0]
            keyList.append(result[i][0])

        for i in range(len(urlList)):
            ws.cell(row=1, column=i + 2).value = valueList[i]
            __dealExcel(urlList[i], i + 2)

def __dealExcel(url, index):

    print('当前处理的文件是=',url)
    with open(url) as f:
        context = f.read()
        partten = re.compile(r'"(.*)" = "(.*)";')
        result = partten.findall(context)

        resultDictionary = {}
        for i in range(len(result)):
            resultDictionary.setdefault(result[i][0], result[i][1])

        for i in range(len(keyList)):
            if keyList[i] in resultDictionary:

                ws.cell(row=i + 2, column=index).value = resultDictionary[keyList[i]]
            else:
                print('字典里面没有该key=',keyList[i])
        # print(resultDictionary)
    wb.save('/Users/apple/Desktop/Strings2Xls/string2xls.xlsx')


if __name__ == '__main__':
    path = "/Users/apple/Desktop/Strings2Xls"
    __getfilename(path)

